package org.gitman.agentplatform.agent.impl.cooperative;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import org.gitman.agentplatform.agent.api.AgentInfo;
import org.gitman.agentplatform.agent.api.AgentPlan;
import org.gitman.agentplatform.agent.api.utils.AbstractAgent;
import org.gitman.agentplatform.agent.api.utils.AgentTools;
import org.gitman.agentplatform.model.utils.GraphTools;

public class ConformableAgent extends AbstractAgent {
	private Stack<Integer> shorthestPath =null;
	
	@Override
	public Integer getStep(Collection<AgentInfo> agentsInRange) {
		updatePlan(agentsInRange, true);
		if(shorthestPath.size() > 0){
			return shorthestPath.peek();
		}else{
			return null;
		}
	}	
	@Override
	public AgentPlan getPlan(int depth, Collection<AgentInfo> agentsInRange) {
		updatePlan(agentsInRange, false);
		int size = shorthestPath.size() < depth ? shorthestPath.size() : depth;
		Stack<Integer> copy = (Stack<Integer>) shorthestPath.clone();
		Integer [] tab = new Integer[size];
		for(int i=0;i<size;i++){
			tab[i] = copy.pop();
		}
		HashMap<Integer[],Double> map = new HashMap<Integer[], Double>();
		map.put(tab, 1.0);
		return new AgentPlan(map);
	}
	private void updatePlan(Collection<AgentInfo> agents, boolean moveNow) {
		Map<Integer, Set<Integer>> vertices2avoid = AgentTools.getVertices2avoid(agents, moveNow);
		shorthestPath = GraphTools.getShorthestPath(graph, agentInfo.getCurrentVertexID(), agentInfo.getEndVertexID(), vertices2avoid, (int) Math.pow(graph.getVertices().size(),2));				

		if(shorthestPath == null){
			shorthestPath = new Stack<Integer>();
		}
		
		// TODO step back, lower ID has higher priority
/*
		if(GraphTools.amIBolckedAndNeed2Move(graph, agentInfo.getCurrentVertexID(), vertices2avoid ){
			shorthestPath = GraphTools.forceStepBack();
		}
		
		if(shorthestPath.size() <= 1){
			shorthestPath = GraphTools.getShorthestPath(graph, agentInfo.getCurrentVertexID(), agentInfo.getEndVertexID());
		}*/
	}
	
}
